//search suggest
(function(){
	var inputting = false

		$(document).on('compositionstart','#search-box-keyword',function(e){
			inputting = true
		}).on('input','#search-box-keyword',function(e){
			if(!inputting){
				updateSuggest()
			}
		}).on('compositionend','#search-box-keyword',function(e){
			inputting = false
			updateSuggest()
		})
		
		var suggestInputTimeout = false
		function updateSuggest(){
			var suggestKeywork = $('#search-box-keyword').val()
			suggestInputTimeout && clearTimeout(suggestInputTimeout)
			suggestInputTimeout = setTimeout(function(){
				suggestInputTimeout = false
				getSuggest(suggestKeywork)
			},500)
		}
		function getSuggest(keyword){
			if(keyword===''){
				$('#search-suggest ul').hide()
				return
			}
			$.ajax({
				type : "GET",
				url : ctx+"/api/search-suggest",
				data : {
					keyword : keyword
				},
				dataType : "json",
				success : function(result) {
					if ( !result || result.statusCode !== '200') {
						$('#search-suggest ul').hide()
						return
					}
					var respon = result.data
					if(!respon || respon.errCode !== 0 ){
						$('#search-suggest ul').hide()
						return
					}
					var suggests = respon.data
					if(!suggests || suggests.length === 0){
						$('#search-suggest ul').hide().empty()
						return
					}
					var keywordEncode = $('<div>').text(keyword.trim()).html()
					var keywordRegax = new RegExp(keywordEncode,'g')
					var lis = ''
					for(var i=0;i<suggests.length;i++){
						var term = $('<div>').text(suggests[i].term).html()
						term = term.replace(keywordRegax,'<i>'+keywordEncode+'</i>')
						lis += '<li><a>'+term+'</a></li>'
					}
					$('#search-suggest ul').html(lis).show()
				}
			})
		}
		
		$(document).on('mousedown','#search-suggest ul li a', function(event) {
		    event.preventDefault();
		}).on('click','#search-suggest ul li a',function(e){
			$('#search-box-keyword').val($(e.currentTarget).text()).blur()
			search()
		})
})()